//
//  MNDFinanceViewController.m
//  minidai
//
//  Created by 谭伟 on 2017/4/25.
//  Copyright © 2017年 迷你金服. All rights reserved.
//投资页

#import "MNDFinanceViewController.h"
//#import <Foundation/Foundation.h>
#import "FTPopOverMenu.h"
#import "MNDInvestSuccessViewController.h"
#import "MNDWebViewController.h"
#import "MNDDepositAlertViewController.h"
#import "MNDDiscountViewController.h"
#import "MNDInvestFailedViewController.h"
#import "MNDRechargeViewController.h"
#import "MNDLoginUserModel.h"
#import "NSString+URLEncode.h"

#import "MNDDepositWebViewController.h"
#import "MNDOpenDeposAlertViewController.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDOpenDepositoryPaymentViewController.h"
#import "MNDOpenDepositoryTenderViewController.h"
#import "MNDOpenDepositoryTransferViewController.h"
#import "MNDUserModel.h"
#import "MNDRiskAssessWebViewController.h"
#import "UIImage+JKColor.h"
#import <TTTAttributedLabel.h>
#import "MNDOpenTermsAuthViewController.h"

//车辆展示图片URL
#define PictureURL @"http://image.miniwangdai.com/upload/image/borrow/artwork/"

@interface MNDFinanceViewController () <UITextFieldDelegate, TTTAttributedLabelDelegate>

//标题
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
//年化收益率
@property (weak, nonatomic) IBOutlet UILabel *yearAprLabel;
//投资期限
@property (weak, nonatomic) IBOutlet UILabel *deadlineLabel;
//剩余可投
@property (weak, nonatomic) IBOutlet UILabel *remainingableLabel;
//充值
@property (weak, nonatomic) IBOutlet UIButton *lackMoneyBtn;
@property (weak, nonatomic) IBOutlet UILabel *lackMoneyTipLabel;
//确认投资
@property (weak, nonatomic) IBOutlet UIButton *confirmInvestBtn;
//顶部背景图
@property (weak, nonatomic) IBOutlet UIImageView *topBackImgV;
//投资金额
@property (weak, nonatomic) IBOutlet UITextField *investMoneyTextField;
//债权转让特有：应付金额view高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *costMoneyConstraint;
@property (weak, nonatomic) IBOutlet UILabel *costMoneyLabel;
@property (weak, nonatomic) IBOutlet UIView *costMoneyView;

//预期收益
@property (weak, nonatomic) IBOutlet UILabel *proEarnMoneyLabel;
//赠利券
@property (weak, nonatomic) IBOutlet UILabel *interestTickerLabel;
//可用余额
@property (weak, nonatomic) IBOutlet UILabel *usableMoneyLabel;
//赠利券
@property (weak, nonatomic) IBOutlet UIView *interestTickerView;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (nonatomic, copy) NSString *userPhone;

@property (nonatomic, strong) MNDUserModel *userModel;

@property (weak, nonatomic) IBOutlet UIButton *accordAgreeButton;
@property (weak, nonatomic) IBOutlet TTTAttributedLabel *accordLabel;


@end

@implementation MNDFinanceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.investMoneyTextField.delegate = self;
    
    self.naviBarTranslucent = YES;
    self.leftBarTintColor = [UIColor whiteColor];
    //充值按钮圆角
    self.lackMoneyBtn.layer.cornerRadius = self.lackMoneyBtn.bounds.size.height*0.5;
    self.lackMoneyBtn.clipsToBounds = YES;
    // Do any additional setup after loading the view.
    [self setupUI];

    //监听输入金额的变化
    [[self.investMoneyTextField rac_textSignal] subscribeNext:^(id x) {
        
        //可投资金额
        NSString *usableInvestStr = [self.self.finaceDetailModel.remainingable_tender stringByReplacingOccurrencesOfString:@"," withString:@""];
        NSString *userInvestStrMoney = [usableInvestStr stringByReplacingOccurrencesOfString:@"." withString:@""];
        double userMoney = userInvestStrMoney.doubleValue/100;
        
        NSString *usable = self.investModel.user_surplus_money;
        NSLog(@"%f",self.investMoneyTextField.text.doubleValue);
        if (self.investMoneyTextField.text.doubleValue >userMoney || self.investMoneyTextField.text.doubleValue >usable.doubleValue) {
            if (userMoney > usable.doubleValue) {
                self.investMoneyTextField.text = usable;
            }else {
                self.investMoneyTextField.text = [NSString stringWithFormat:@"%.2f",userMoney];
            }
        }
        CGFloat yearApr = self.finaceDetailModel.borrow_year_apr.doubleValue;
        CGFloat daedline = self.finaceDetailModel.borrow_deadline.doubleValue;
        double num = self.investMoneyTextField.text.doubleValue;
        //计算利益
        double money = num*yearApr*daedline/12/100*0.95 ;
        self.proEarnMoneyLabel.text = [NSString stringWithFormat:@"%.2f",money];

    }];
    
    //赠利券点击事件添加
    [self.interestTickerView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickinterestTickerView)]];
    
    [self addAgreementLabelAttribute];
    
    [self.confirmInvestBtn setBackgroundImage:[UIImage jk_imageWithColor:[UIColor colorWithRed:238/255.0 green:109/255.0 blue:71/255.0 alpha:1.0]] forState:UIControlStateNormal];
    [self.confirmInvestBtn setBackgroundImage:[UIImage jk_imageWithColor:kColorGray] forState:UIControlStateDisabled];
    [self initBackButtonItem];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if ([MNDLoginUserModel isUserLogin]) {
        
        [self loadUserInfo];
        
        [self loadUserPhone];
    }
    [self loadData];
    
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    UIImage *image = [UIImage jk_imageWithColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:0.3]];
    self.navigationController.navigationBar.shadowImage = image;
    
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
}

- (void)initBackButtonItem {
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    UIImage *itemImage = [UIImage imageNamed:@"navi_back_btn_black"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage: itemImage
                                                             style: UIBarButtonItemStylePlain
                                                            target: self
                                                            action: @selector(backAction:)];
    
    
    [item setTintColor:kColorBlack];
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = item;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, item];
    }
    for (UIBarButtonItem *item in self.navigationItem.leftBarButtonItems) {
        [item setTintColor:[UIColor whiteColor]];
    }
}

- (void)backAction:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addAgreementLabelAttribute {
    //设置高亮颜色
    self.accordLabel.highlightedTextColor = kColorBlack;
    //检测类型
    self.accordLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    //代理
    self.accordLabel.delegate = self;
    //不显示下划线
    self.accordLabel.linkAttributes = @{(NSString *)kCTUnderlineStyleAttributeName: [NSNumber numberWithBool:NO]};
    
    NSString *text = @"我已阅读并同意签署《借款协议》《网络借贷风险和禁止性行为提示书》";
    [self.accordLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        
        UIColor *linkColor = [UIColor colorWithRed:238/255.0 green:109/255.0 blue:71/255.0 alpha:1.0];
        NSRange linkRange1 = [[mutableAttributedString string] rangeOfString:@"我已阅读并同意签署" options:NSCaseInsensitiveSearch];
        NSRange linkRange2 = [[mutableAttributedString string] rangeOfString:@"《借款协议》" options:NSCaseInsensitiveSearch];
        NSRange linkRange3 = [[mutableAttributedString string] rangeOfString:@"《网络借贷风险和禁止性行为提示书》" options:NSCaseInsensitiveSearch];
        
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorLightGray} range:linkRange1];
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: linkColor} range:linkRange2];
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: linkColor} range:linkRange3];
        
        return mutableAttributedString;
    }];
    
    NSRange linkRange1 = [text rangeOfString:@"我已阅读并同意签署" options:NSCaseInsensitiveSearch];
    NSURL *url1 = [NSURL URLWithString:@"http://baidu.com"];
    NSRange linkRange2 = [text rangeOfString:@"《借款协议》" options:NSCaseInsensitiveSearch];
    NSURL *url2 = [NSURL URLWithString:[API_BASE_URL stringByAppendingString:kLoanAccordUrl]];
    NSRange linkRange3 = [text rangeOfString:@"《网络借贷风险和禁止性行为提示书》" options:NSCaseInsensitiveSearch];
    NSURL *url3 = [NSURL URLWithString:[API_BASE_URL stringByAppendingString:kRiskTipAccordUrl]];
    [self.accordLabel addLinkToURL:url1 withRange:linkRange1];
    [self.accordLabel addLinkToURL:url2 withRange:linkRange2];
    [self.accordLabel addLinkToURL:url3 withRange:linkRange3];
}

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    if ([url.absoluteString containsString:@"baidu.com"]) {
        [self agreeAccordAction:self.accordAgreeButton];
        
        return;
    }
        MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
        webVC.webViewUrl = url.absoluteString;
        webVC.loadType = LoadTypeLink;
        webVC.naviBarHidden = NO;
    
    if ([url.absoluteString isEqualToString:[API_BASE_URL stringByAppendingString:kRiskTipAccordUrl]]) {
        webVC.title = @"网络借贷风险和禁止性行为提示书";
    } else {
        webVC.title = @"借款协议";
    }
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:webVC];
    [self presentViewController:navVC animated:YES completion:^{
    
    }];
}

- (IBAction)agreeAccordAction:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    
    self.confirmInvestBtn.enabled = sender.isSelected;
}

#pragma mark -搭建界面
- (void)setupUI {
    self.investMoneyTextField.clearsOnBeginEditing = YES;
    //self.navigationController.navigationBar.barTintColor =
    if ([self.finaceDetailModel.borrow_title containsString:@"债权转让"]) {//债权转让
        //确认投资按钮颜色及背景图
        self.confirmInvestBtn.backgroundColor = kBlueColor;
        [self.confirmInvestBtn setBackgroundImage:nil forState:UIControlStateNormal];
        //nav背景颜色
        self.topBackImgV.image = [UIImage imageNamed:@"creditor_detail_wave"];
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
       //应付金额view
        self.costMoneyView.hidden = NO;
        self.costMoneyConstraint.constant = 100;
        self.costMoneyLabel.textColor = kBlueColor;
        //预期收益
        self.proEarnMoneyLabel.textColor = kBlueColor;
        
        //赠利券
        self.interestTickerLabel.textColor = kBlueColor;
        
        //充值文字与按钮
        [self.lackMoneyBtn setBackgroundImage:[UIImage imageNamed:@"finance_invest_btn"] forState:UIControlStateNormal];
        [self.lackMoneyBtn setBackgroundColor:kOrangeColor];
        self.lackMoneyTipLabel.textColor = kOrangeColor;
        
    } else {//其他
        //确认投资按钮颜色及背景图
        [self.confirmInvestBtn setBackgroundImage:[UIImage imageNamed:@"finance_invest_btn"] forState:UIControlStateNormal];
        //nav背景颜色
        self.topBackImgV.image = [UIImage imageNamed:@"finance_detail_header_scrolled"];

        //应付金额view
        self.costMoneyView.hidden = YES;
        self.costMoneyConstraint.constant = 0;
        self.costMoneyLabel.textColor = kOrangeColor;
        
        //预期收益
        self.proEarnMoneyLabel.textColor = kOrangeColor;
        
        //赠利券
        self.interestTickerLabel.textColor = kOrangeColor;
        
        //充值文字与按钮
        [self.lackMoneyBtn setBackgroundImage:nil forState:UIControlStateNormal];
        [self.lackMoneyBtn setBackgroundColor:kBlueColor];
        self.lackMoneyTipLabel.textColor = kBlueColor;
    }
//    //点击赠利券
//    [self.interestTickerView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickDiscountView:)]];
}

#pragma mark -加载数据
- (void)loadData {
    [self.view beginLoading];
    __weak typeof(self) weakSelf = self;
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"borrow_code":self.borrowCode}];
    
    [APIManager sendRequestWithPath:API_FINANCE_DETAIL parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakSelf.finaceDetailModel = [MNDFinaceDetailModel mj_objectWithKeyValues:responseModel.data];
            
            [weakSelf configContents];
            [weakSelf loadInvestData];
        } else {
            [weakSelf.view endLoading];
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            [weakSelf backToPrevious];
        }
    } onFailure:^(NSError *error) {
        [weakSelf.view endLoading];
        [NetworkProgressHUD showHudNetworkError:error];
        [weakSelf backToPrevious];
    }];
}

//获取投资数据
- (void)loadInvestData{
    WeakSelf(self)
    //请求投资
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"borrow_code":self.borrowCode}];
    
    [APIManager sendRequestWithPath:API_INVEST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        [weakself.view endLoading];
        if(responseModel.status == ResponseSuccess) {
            weakself.investModel = [MNDInvestModel mj_objectWithKeyValues:responseModel.data];
            NSLog(@"response: %@", responseModel.data);
            [weakself configInvestContent];
        } else{
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
            [weakself backToPrevious];
        }
    } onFailure:^(NSError *error) {
        [weakself.view endLoading];
        [NetworkProgressHUD showHudNetworkError:error];
        [weakself backToPrevious];
    }];
}

- (void)backToPrevious {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}

- (void)loadUserInfo {
    
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_USER_BASE_INFO parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            weakself.userModel = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
            
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

/**
 获取存管手机号
 */
- (void)loadUserPhone {
    
    WeakSelf(self);
    
    NSDictionary *param = [MNDSign signedParam];
    [APIManager sendRequestWithPath:API_DEPOSIT_GET_PHONE parameters:param method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakself.userPhone = responseModel.data;
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configContents {
    self.titleLabel.text = _finaceDetailModel.borrow_title;
    self.yearAprLabel.text = _finaceDetailModel.borrow_year_apr;
    self.deadlineLabel.text = [NSString stringWithFormat:@"%@个月",_finaceDetailModel.borrow_deadline];
    self.remainingableLabel.text = [NSString stringWithFormat:@"%@",_finaceDetailModel.remainingable_tender];
}

- (void)configInvestContent {
    if (self.investModel.activation_coupon_sum.integerValue >0) {
        self.interestTickerLabel.text = @"已使用赠利券";
    } else{
        self.interestTickerLabel.text = [NSString stringWithFormat:@"未激活的赠利券数量:%@",self.investModel.need_coupon_sum];
    }
    if (self.investModel.activation_coupon_sum.integerValue <= 0 && self.investModel.need_coupon_sum.integerValue <= 0) {
        //赠利券
        self.interestTickerLabel.textColor = kColorLightGray;
        self.interestTickerLabel.text = [NSString stringWithFormat:@"暂无可用赠利券"];
    }
    self.usableMoneyLabel.text = self.investModel.user_surplus_money;
    if (self.usableMoneyLabel.text.doubleValue > 0) {//如果有钱不显示充值
        self.lackMoneyBtn.hidden = YES;
        self.lackMoneyTipLabel.hidden = YES;
    } else {//没钱则显示充值
        self.lackMoneyBtn.hidden = NO;
        self.lackMoneyTipLabel.hidden = NO;
    }
    //设置默认投资金额
    //可投资金额
    NSString *usableInvestStr = [self.finaceDetailModel.remainingable_tender stringByReplacingOccurrencesOfString:@"," withString:@""];
    NSString *userInvestStrMoney = [usableInvestStr stringByReplacingOccurrencesOfString:@"." withString:@""];
    //可投金额
    double userInvestMoney = userInvestStrMoney.doubleValue/100;
    NSString *usable = self.investModel.user_surplus_money;
    
    if (userInvestMoney > usable.doubleValue) {
        self.investMoneyTextField.text = [NSString stringWithFormat:@"%@",usable];
    } else {
        self.investMoneyTextField.text = [NSString stringWithFormat:@"%.2f",userInvestMoney];
    }
    //计算预期收益
    CGFloat yearApr = self.finaceDetailModel.borrow_year_apr.doubleValue;
    CGFloat daedline = self.finaceDetailModel.borrow_deadline.doubleValue;
    double num = self.investMoneyTextField.text.doubleValue;
    //计算利益
    CGFloat money = num*yearApr*daedline/12/100*0.95 ;
    self.proEarnMoneyLabel.text = [NSString stringWithFormat:@"%.2f",money];
}

#pragma mark -交互
//点击nav更多按钮
- (IBAction)clickMoreButton:(UIButton *)sender {
   
    FTPopOverMenuConfiguration *configuration = [FTPopOverMenuConfiguration defaultConfiguration];
    configuration.textColor = kColorGray;
    configuration.tintColor = [UIColor whiteColor];
    configuration.borderColor = [UIColor whiteColor];
    configuration.menuIconMargin = 18;
    [FTPopOverMenu showForSender:sender withMenuArray:@[@"首页",@"客服",@"帮助中心"] imageArray:@[@"popup_menu_home",@"popup_menu_service",@"popup_menu_help"] doneBlock:^(NSInteger selectedIndex) {
        if (selectedIndex == 0) {//首页
            
            self.tabBarController.selectedIndex = 0;
            
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }else if (selectedIndex == 1) {//客服
            MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
            MNDWebViewController *bbsVC = [[MNDWebViewController alloc]init];
            NSLog(@"%@",user.user_name);
            NSString *str = [NSString stringWithFormat:@"%@?user_id=%@&user_name=%@", kCustomerServiceURLStr, user.user_id, user.user_name];
            bbsVC.webViewUrl = str;
            bbsVC.title = @"在线客服";
            bbsVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:bbsVC animated:YES];
            
        }else {//帮助中心
            MNDWebViewController *mndWebViewController = [[MNDWebViewController alloc]init];
            mndWebViewController.hidesBottomBarWhenPushed = YES;
            mndWebViewController.webViewUrl = [NSString stringWithFormat:@"%@%@", WebBaseURL, HelpCenterURL];
            mndWebViewController.naviBarHidden = YES;
            [self.navigationController pushViewController:mndWebViewController animated:YES];
        }

    } dismissBlock:nil];
}

//点击充值按钮
- (IBAction)clickLackMoneyBtn:(UIButton *)sender {

    [self goRecharge];
}

/**
 充值
 */
- (void)goRecharge {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Recharge" bundle:nil];
    MNDRechargeViewController *rechargeVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDRechargeViewController"];
    rechargeVC.isFromTender = YES;
    [self.navigationController pushViewController:rechargeVC animated:YES];
}

//点击赠利券跳转
- (void)clickDiscountView:(UIButton *)btn {

}

//
- (IBAction)backVC:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

//UITextFieldDelegate
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//确认投标
- (IBAction)clickConfirmBtn:(UIButton *)sender {
    
    [self confirmInvestSuccess];
}

//点击进入赠利券列表
- (void)clickinterestTickerView {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
    MNDDiscountViewController *discountVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDDiscountViewController"];
    [self.navigationController pushViewController: discountVC animated:YES];
    //    [NetworkProgressHUD showHudMsg:@"页面制作中，请耐心等候"];
}

- (void)showRiskAlertView {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您还没有完成[出借用户风险等级测评]，根据金融监管政策要求，用户需要先完成评估才能出借。" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"去测评" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
        
        MNDRiskAssessWebViewController *riskVC = [[MNDRiskAssessWebViewController alloc]init];
        riskVC.webViewUrl = self.userModel.evaluationUrl;
        riskVC.indexOfViewController = index;
        riskVC.title = @"风险测评";
        [self.navigationController pushViewController:riskVC animated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

/**
 设置交易密码
 */
- (void)loadPaymentPassword {
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SET_PASSWORD parameters:[MNDSign signedParamWithDict:@{@"channel": @"app"}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"设置交易密码";
            NSInteger index = [weakself.navigationController.viewControllers indexOfObject:weakself];
            webVC.fromNaviIndex = index;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

#pragma mark -判断投资是否成功
- (void)confirmInvestSuccess{
    //输入金额判断
    if (self.investMoneyTextField.text.length > 0 && self.investMoneyTextField.text.doubleValue > 0) {
        
        WeakSelf(self);
        [NetworkProgressHUD showHud];
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
        //请求投资
        NSString *investMoney = self.investMoneyTextField.text;
        
        NSDictionary *params = [MNDSign signedParamWithDict:@{@"borrow_code":self.finaceDetailModel.borrow_code,@"tender_money":investMoney}];
        [APIManager sendRequestWithPath:API_INVEST parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
            
            [NetworkProgressHUD hideHud];
            
            if (responseModel.status == ResponseSuccess) {
                
                MNDInvestSuccessViewController *investSucessVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDInvestSuccessViewController"];
                investSucessVC.investMoneyStr = self.investMoneyTextField.text;
                investSucessVC.proEarnMoneyStr = self.proEarnMoneyLabel.text;
                investSucessVC.borrowCode = self.borrowCode;
                investSucessVC.tenderId = responseModel.data[@"tender_id"];
                [weakself.navigationController pushViewController:investSucessVC animated:YES];
            } else {
                NSDictionary *msgDict = responseModel.msg;
                if ([msgDict.allKeys containsObject:@"sign"]) {
                    if ([responseModel.msg[@"sign"] isEqualToString:kOpenAccount] ||
                        [responseModel.msg[@"sign"] isEqualToString:kSetPassword] ||
                        [responseModel.msg[@"sign"] isEqualToString:kSignPayment] ||
                        [responseModel.msg[@"sign"] isEqualToString:kSignAutoTender] ||
                        [responseModel.msg[@"sign"] isEqualToString:kSignAutoTransfer] ||
                        [responseModel.msg[@"sign"] isEqualToString:kRiskEvaluation] ||
                        [responseModel.msg[@"sign"] isEqualToString:kBandcard] ||
                        [responseModel.msg[@"sign"] isEqualToString:kExpiredSignPayment] ||
                        [responseModel.msg[@"sign"] isEqualToString:kExpiredAutotender]
                        ) {
                        [weakself showDepositAlertWithModel:responseModel];
                    }else if([responseModel.msg[@"sign"] isEqualToString:@"tender_money"]) {
                        [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                    }else {
                        MNDInvestFailedViewController *failedVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDInvestFailedViewController"];
                        [weakself.navigationController pushViewController:failedVC animated:YES];
                    }
                    
                } else {
                    MNDInvestFailedViewController *failedVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDInvestFailedViewController"];
                    [weakself.navigationController pushViewController:failedVC animated:YES];
                }
            }
        } onFailure:^(NSError *error) {
            [NetworkProgressHUD showHudNetworkError:error];
        }];
    }else {
        [NetworkProgressHUD showHudMsg:@"请输入出借金额"];
    }
}

- (void)showDepositAlertWithModel:(ResponseModel *)response {
    NSString *signStr = response.msg[@"sign"];
    
    
    
    //开通存管账户
    if ([signStr isEqualToString:kOpenAccount]) {
        
        [self showOpenAccountAlertWithModel:response];
        return;
    }
    
    //风险等级未评测
    if ([signStr isEqualToString:kRiskEvaluation]) {
        
        [self showRiskAlertView];
        return;
    }
    
//    if ([signStr isEqualToString:@"set_password"]) {
        __weak MNDOpenDeposAlertViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDeposAlertViewController description]];
        
        __weak UIView *alertView = alertVC.view;
        [KeyWindow addSubview:alertView];
        [self.tabBarController addChildViewController:alertVC];
        
        WeakSelf(self);
        
        [alertVC.confirmButton bk_addEventHandler:^(id sender) {
            [alertView removeFromSuperview];
            [alertVC removeFromParentViewController];
            
            [weakself toOpenDepositoryWithModel:response];
            
        } forControlEvents:UIControlEventTouchUpInside];
        
        alertVC.alertMessage = response.msg[@"error"];
        alertVC.alertType = response.msg[@"sign"];
//    }
    
}

- (void)showOpenAccountAlertWithModel:(ResponseModel *)response {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDDepositAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:[MNDDepositAlertViewController description]];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self.tabBarController addChildViewController:alertVC];
    
    __weak typeof(self) weakSelf = self;
    
    [alertVC.depositBtn bk_addEventHandler:^(id sender) {
        [springView removeFromSuperview];
        [alertVC removeFromParentViewController];
        [weakSelf toOpenDepositoryWithModel:response];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    [alertVC.closeBtn bk_addEventHandler:^(id sender) {
        
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainerView.frame = CGRectMake(alertVC.alertContainerView.frame.origin.x, kScreenHeight, alertVC.alertContainerView.frame.size.width, alertVC.alertContainerView.frame.size.height);
            alertVC.closeBtn.frame = CGRectMake(alertVC.closeBtn.frame.origin.x, kScreenHeight, alertVC.closeBtn.frame.size.width, alertVC.closeBtn.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)toOpenDepositoryWithModel:(ResponseModel *)response {
    
    NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
    
    NSString *signStr = response.msg[@"sign"];
    //开通存管
    if ([signStr isEqualToString:kOpenAccount]) {
        MNDOpenDepositoryViewController *realVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryViewController description]];
        realVC.fromNaviIndex = index;
        
        [self.navigationController pushViewController:realVC animated:YES];
        
        return;
    }
    //设置交易密码
    if ([signStr isEqualToString:kSetPassword]) {
        
        [self loadPaymentPassword];
        return;
    }
    
    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment] || [signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender] || [signStr isEqualToString:kSignAutoTransfer]) {
        MNDOpenTermsAuthViewController *openTermsAuthVC = [UIStoryboard viewControllerWithIdentifier:@"MNDOpenTermsAuthViewController"];
        openTermsAuthVC.fromNaviIndex = index;
        [self.navigationController pushViewController:openTermsAuthVC animated:YES];
        return;
    }
//    //设置缴费授权
//    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment]) {
//        
//        MNDOpenDepositoryPaymentViewController *paymentVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryPaymentViewController description]];
//        paymentVC.fromNaviIndex = index;
//        
//        [self.navigationController pushViewController:paymentVC animated:YES];
//        
//        return;
//    }
//    //设置自动投标
//    if ([signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender]) {
//        
//        MNDOpenDepositoryTenderViewController *tenderVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTenderViewController description]];
//        tenderVC.isResign = [signStr isEqualToString:kExpiredAutotender];
//        if (self.userPhone.length > 0) {
//            tenderVC.fromNaviIndex = index;
//            tenderVC.phoneNumber = self.userPhone;
//            
//            [self.navigationController pushViewController:tenderVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//        return;
//    }
//    //设置自动债转
//    if ([signStr isEqualToString:kSignAutoTransfer]) {
//        
//        MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
//        if (self.userPhone.length > 0) {
//            transferVC.fromNaviIndex = index;
//            transferVC.phoneNumber = self.userPhone;
//            
//            [self.navigationController pushViewController:transferVC animated:YES];
//        } else {
//            [self loadUserPhone];
//        }
//        return;
//    }
//    
    //风险等级未评测
    if ([signStr isEqualToString:kRiskEvaluation]) {
        
        [self showRiskAlertView];
        return;
    }
}

//设置textfield输入内容
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.investMoneyTextField) {
        NSScanner      *scanner    = [NSScanner scannerWithString:string];
        NSCharacterSet *numbers;
        NSRange         pointRange = [textField.text rangeOfString:@"."];
        
        if ( (pointRange.length > 0) && (pointRange.location < range.location  || pointRange.location > range.location + range.length) )
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        }
        else
        {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
        }
        
        if ( [textField.text isEqualToString:@""] && [string isEqualToString:@"."] )
        {
            return NO;
        }
        
        short remain = 2; //默认保留2位小数
        
        NSString *tempStr = [textField.text stringByAppendingString:string];
        NSUInteger strlen = [tempStr length];
        if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
            if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
                return NO;
            }
            if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
                return NO;
            }
        }
        NSRange zeroRange = [textField.text rangeOfString:@"0"];
        if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
            if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){ //当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
                textField.text = string;
                return NO;
            }else{
                if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                    if([string isEqualToString:@"0"]){
                        return NO;
                    }
                }
            }
        }
        
        NSString *buffer;
        if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
        {
            return NO;
        }
    }
    
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
